import socket
import threading

def createServer(bind_ip, port, connect_number=5):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((bind_ip, port))
    server.listen(connect_number)

    print('create server: %s:%s'% (bind_ip, port))
    return server

def client_handle(client_socket, package_size=1024):
    while client_socket:
        try:
            req = client_socket.recv(package_size)
        except IOError:
            # 客户端终止关闭
            return
        print('client send: %s' % req)
        if b'test' in req:
            client_socket.send(b'password:')
            print('send password')
            continue
        if b'123321' in req:
            client_socket.send(b'login success')
            print('send login success')
            continue
        client_socket.send(('server recv: %s' % req).encode())
        if b'quit' in req:
            client_socket.close()
            client_socket = None


if __name__ == '__main__':
    server = createServer('127.0.0.1', 8899)
    while True:
        client, addr = server.accept()
        print('connect from: %s:%s' % (addr[0], addr[1]))
        client.send('Welcome !\nusername:'.encode())
        handler = threading.Thread(target=client_handle, args=(client,))
        handler.start()